const socketio= require("socket.io");
const db= require('./db.js');
var io,
    guestNumber= 1,  //产生默认用户名的计数编码
    nickNames= {},  //记录用户昵称
    namesUsed= [],
    currentRoom= {};  //记录用户的当前房间

exports.listen= function(server){

    db.select_user_count((v)=>{
        guestNumber+=v[0].length;
    });
    io= socketio.listen(server);
    // io.set("log level", 1);
    io.on('connection', function(socket){  //定义每个用户连接的处理逻辑
        // socket.handshake.headers.cookie("socketID","尼玛");

        console.log('a user connected');
        assignGuestName(socket);  //在用户连接上来时赋予其一个访客名
        joinRoom(socket, "lobby");  //使用户默认加入房间
        handleMessageBroadcasting(socket);  //发送聊天消息
        handleNameChangeAttempts(socket);  //更名处理
        handleRoomJoining(socket);  // 创建房间
        handleRecords(socket);  //获取用户的聊天记录
        handleClientDisconnection(socket);  //退出
    });
    // io.engine.generateId = (req) => {
    //     console.log('进入1',req.headers.cookie);
    //     console.log('进入2',req.headers);
    //     return "custom" + guestNumber++; // custom id must be unique
    // }
    // setTimeout(()=>{
    //     io.close(()=>{
    //         console.log('关闭socket服务器')
    //     });
    // },5000)

}

//设置当前用户id作为cookie值
function set_cookie(socket,name,day=7) {
    var date = new Date();
    date.setTime(date.getTime()+(day*24*60*60*1000)); // set day value to expiry
    var expires = "; expires="+date.toGMTString();
    socket.request.headers.cookie = "socket_name="+name+expires+"; path=/";
    console.log('cookie',get_cookie(socket.request.headers.cookie,'socket_name') );
}

// 获取指定名称的cookie
function get_cookie(cookie,name){
    var strcookie = cookie;//获取cookie字符串
    if(!strcookie) return ''
    var arrcookie = strcookie.split("; ");//分割
    //遍历匹配
    for ( var i = 0; i < arrcookie.length; i++) {
        var arr = arrcookie[i].split("=");
        if (arr[0] == name){
            return arr[1];
        }
    }
    return "";
}

//分配用户昵称
function assignGuestName(socket){
    var socket_name= get_cookie(socket.request.headers.cookie,'socket_name');
    console.log('获取socket_name的cookie:',socket_name);
    var name;  //生成新昵称
    if(socket_name){
        name=socket_name;
    } else{
        name="guest"+guestNumber;
        set_cookie(socket,name,10); //在客户端存储name
        db.insert_user(socket.id,name,new Date());  //新用户名存入数据库
    }

    nickNames[socket.id]= name;  //把用户昵称跟客户端连接ID关联上

    socket.emit("nameResult",{  //让用户知道他们的昵称
        success: true,
        name: name
    });
    // db.select_user(name,function(v){
    //     console.log('v:',v.length);
    // });
    namesUsed.push(name);  //存放已经被占用的昵称
    guestNumber+=1;  //增加用来生成昵称的计数器
}

//与进入聊天室相关的逻辑
function joinRoom(socket, room){
    socket.join(room,()=>{
        currentRoom[socket.id]= room;  //记录用户的当前房间
        socket.emit("joinResult", {room});  //让用户知道他们进入了新的房间
        socket.broadcast.to(room).emit("message", {  //让房间里的其他用户知道有新用户进入了房间
            text: nickNames[socket.id]+"用户加入该房间。"
        })
        var currentUsers=[];  //当前房间的用户
        for(let i in currentRoom){
            if(i !== socket.id && currentRoom[i]===room){
                currentUsers.push(nickNames[i])
            }
        }
        socket.emit("currentUsers", currentUsers);  //将房间里其他用户的汇总发给这个用户
        socket.broadcast.to(room).emit("currentUsersAdd", nickNames[socket.id]);  //增加用户

    });  //让用户进入房间


    // console.log('总用户数：',socket.client.server.eio.clientsCount)
    // console.log('总用户：')
    // for(let i in socket.nsp.connected){
    //     console.log(i)
    // }
}

//发送聊天消息
function handleMessageBroadcasting(socket){
    socket.on("chat_message", function(message){
        console.log('socket:',socket.rooms)

        // socket.emit('get_message', nickNames[socket.id]+": "+message);
        // socket.broadcast.emit('get_message', nickNames[socket.id]+": "+message);
        // io.in(Object.keys(socket.rooms)[Object.keys(socket.rooms).length-1]).emit("get_message", nickNames[socket.id]+": "+message);
        var room= Object.keys(socket.rooms)[Object.keys(socket.rooms).length-1];
        io.in(room).emit("get_message", {text: message, name: nickNames[socket.id]});
        db.insert_record(nickNames[socket.id],message,room,new Date());
    });
}

//更名请求的处理逻辑
function handleNameChangeAttempts(socket){
    socket.on("nameAttempt", function(name){
        console.log('nameAttempt:',name)
        if(name.indexOf("Guest") == 0){
            socket.emit("nameResult", {
                success: false,
                message: "姓名不能以'Guest'开头。"
            });
        } else{
            if(namesUsed.indexOf(name) === -1){
                var previousName= nickNames[socket.id];
                var previousNameIndex= namesUsed.indexOf(previousName);
                namesUsed.push(name);
                nickNames[socket.id]= name;
                delete namesUsed[previousNameIndex];
                socket.emit("nameResult", {
                    success: true,
                    message: "用户名修改成功！",
                    name
                });
                socket.broadcast.to(currentRoom[socket.id]).emit("message", {
                    text: previousName+" 更名为："+name+'。'
                });
            } else{
                socket.emit("nameResult", {
                    success: false,
                    message: "That name is already in use."
                })
            }
        }

    });
}


// 创建房间
function handleRoomJoining(socket){
    socket.on("join", function(room){
        socket.leave(currentRoom[socket.id],()=>{
            socket.broadcast.to(currentRoom[socket.id]).emit("currentUsersMinus", nickNames[socket.id]);  //通知其他用户当前退出的用户
            socket.broadcast.to(currentRoom[socket.id]).emit("message", {text: nickNames[socket.id]+"用户退出该房间。"}); //退出后通知该房间的其他用户
            joinRoom(socket, room.newRoom);
        });
    });
}

function handleRecords(socket){   //获取用户的聊天记录
    socket.on("get_records", function(){
        db.select_record(nickNames[socket.id],function(v){
            socket.emit("get_records",v)
        })
    })
}

//用户断开连接
function handleClientDisconnection(socket){
    socket.on("disconnect", function(){
        console.log('disconnect:', nickNames[socket.id])
        var nameIndex= namesUsed.indexOf(nickNames[socket.id]);
        delete namesUsed[nameIndex];
        delete nickNames[socket.id];
        delete currentRoom[socket.id];
    });
}
